package repository

import (
	"context"
	"server_go/internal/model"
)

type UsersRepository interface {
	GetUsersByAccount(ctx context.Context, account string) (*model.Users, error)
	CreateUsers(ctx context.Context, m *model.Users) error
	GetUserByID(ctx context.Context, userID uint) (*model.Users, error)
	UpdatePassword(ctx context.Context, userID uint, newPassword string) error
}

func NewUsersRepository(
	repository *Repository,
) UsersRepository {
	return &usersRepository{
		Repository: repository,
	}
}

type usersRepository struct {
	*Repository
}

func (r *usersRepository) GetUsersByAccount(ctx context.Context, account string) (*model.Users, error) {
	var users model.Users
	err := r.DB(ctx).Where("account = ? ", account).First(&users).Error
	if err != nil {
		return nil, err
	}
	return &users, nil
}
func (r *usersRepository) CreateUsers(ctx context.Context, user *model.Users) error {
	return r.db.WithContext(ctx).Create(user).Error
}

// 查询用户通过ID
func (r *usersRepository) GetUserByID(ctx context.Context, userID uint) (*model.Users, error) {
	var user model.Users
	err := r.db.WithContext(ctx).Where("id = ?", userID).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// 更新用户密码
func (r *usersRepository) UpdatePassword(ctx context.Context, userID uint, newPassword string) error {
	return r.DB(ctx).
		Model(&model.Users{}).
		Where("id = ?", userID).
		Update("password", newPassword).
		Error
}
